package handler

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"math/rand"
	"regexp"
	"server/basic/global"
	"server/basic/inits"
	"server/models"
	__ "server/proto"
	"time"
)

type Server struct {
	__.UnimplementedUserServer
}

// 手机号格式的判断
func IsNum(phone string) bool {
	pattern := `^1[3-9]\d{9}$`
	reg := regexp.MustCompile(pattern)
	return reg.MatchString(phone)
}

// SayHello implements helloworld.GreeterServer
func (s *Server) Sendsms(_ context.Context, in *__.SendsmsRequest) (*__.SendsmsResponse, error) {
	if len(in.Mobile) != 11 || !IsNum(in.Mobile) {
		return nil, errors.New("手机号格式错误")
	}
	code := rand.Intn(9000) + 1000
	inits.RedisClient.Set(context.Background(), "sendsms"+in.Mobile+in.Score, code, time.Minute*6)
	return &__.SendsmsResponse{}, nil
}
func (s *Server) Login(_ context.Context, in *__.LoginRequest) (*__.LoginResponse, error) {
	if len(in.Mobile) != 11 || !IsNum(in.Mobile) {
		return nil, errors.New("手机号格式错误")
	}
	get := inits.RedisClient.Get(context.Background(), "sendsms"+in.Mobile+"login")
	if get.Val() != in.Sendsms {
		return nil, errors.New("验证码错误")
	}
	var user models.Users
	global.DB.Find(&user)
	return &__.LoginResponse{
		Id: user.Id,
	}, nil
}
func (s *Server) UpdateUser(_ context.Context, in *__.UpdateUserRequest) (*__.UpdateUserResponse, error) {
	update := models.Users{
		Id:       in.Id,
		UserName: in.UserName,
		NickName: in.NickName,
		Sex:      in.Sex,
		Mileage:  in.Mileage,
	}
	return &__.UpdateUserResponse{
		Id: update.Id,
	}, nil
}
func (s *Server) Order(_ context.Context, in *__.OrderRequest) (*__.OrderResponse, error) {
	order := uuid.NewString()
	
	add := models.LxhOrder{
		OrderCode:   order,
		OrderStatus: in.OrderStatus,
		PassengerId: in.PassengerId,
		StartAddr:   in.StartAddr,
		EndEnd:      in.EndEnd,
		Driver:      in.Driver,
		PayStatus:   in.PayStatus,
		PayType:     in.PayType,
		OrderType:   in.OrderType,
	}
	global.DB.Create(&add)
	return &__.OrderResponse{
		Id: add.Id,
	}, nil
}
func (s *Server) OrderList(_ context.Context, in *__.OrderListRequest) (*__.OrderListResponse, error) {
	var find []models.LxhOrder
	global.DB.Find(&find)
	var finds []*__.List
	for _, v := range find {
		finds = append(finds, &__.List{
			OrderCode:   v.OrderCode,
			OrderStatus: v.OrderStatus,
			PassengerId: v.PassengerId,
			StartAddr:   v.StartAddr,
			EndEnd:      v.EndEnd,
			Driver:      v.Driver,
			PayStatus:   v.PayStatus,
			PayType:     v.PayType,
			OrderType:   v.OrderType,
		})

	}
	return &__.OrderListResponse{
		List: finds,
	}, nil
}
func (s *Server) Comment(_ context.Context, in *__.CommentRequest) (*__.CommentResponse, error) {
	add := models.Comments{
		UserId:   in.Userid,
		DriverId: in.Driverid,
		Comment:  in.Comment,
	}
	global.DB.Create(&add)
	return &__.CommentResponse{
		Id: add.Id,
	}, nil
}
